package com.whfp.coky.ble.print

import android.os.Looper
import android.os.Message
import com.android.print.sdk.PrinterConstants
import com.android.print.sdk.PrinterInstance
import com.whfp.coky.ui.base.BaseActivity

/**
 *
 *
 * created by coky on 2022/3/29
 */
class PrintBtController(var activity:BaseActivity<*,*>,listener:PrintListener) {
    var isConnSuccessPrint: Boolean = false//打印机连接成功标识
    private var printMac:String?=null
        set(value) {
            field = value
        }

    private var mPrinter: PrinterInstance? = null
    private var myOpertion: IPrinterOpertion? = null
    private val pHandler = object : android.os.Handler(Looper.getMainLooper()) {
        //    打印handler处理中心
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                PrinterConstants.Connect.SUCCESS -> {//连接成功
                    isConnSuccessPrint = true
                    activity.hideDialog()
                    mPrinter = myOpertion!!.printer
                    printMac?.let {
                        listener.printConnSuccess(it)
                    }
                }
                PrinterConstants.Connect.FAILED -> {//连接失败
                    isConnSuccessPrint = false
                    activity.hideDialog()
                    printMac?.let {
                        listener.printConnFailed(it)
                    }
                }
                PrinterConstants.Connect.CLOSED -> {//连接断开
                    isConnSuccessPrint = false
                    listener.printConnClosed()
                }
            }
        }
    }



    fun connPrint(mac:String){
        if (isConnSuccessPrint){
            disConnPrint()
        }else{
            printMac = mac
            myOpertion = BluetoothOperation(activity, pHandler, mac)
        }
    }

    fun disConnPrint(){
        myOpertion?.close()
        myOpertion = null
        mPrinter = null
    }


    interface PrintListener{
        fun printConnSuccess(devMac:String)
        fun printConnFailed(devMac:String)
        fun printConnClosed()
    }
}